package com.wzy.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class for Servlet: UploadAffixServlet
 * 
 */
public class UploadAffixServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	
	String uploadPath = "";
	private int maxPostSize = 100 * 1024 * 1024;
	public UploadAffixServlet() {
		super();
	}
	public void init() throws ServletException {
		this.uploadPath = this.getServletContext().getRealPath(
				"/AffixFile/");
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		uploadRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		uploadRequest(request, response);
	}
	/*
	 * 用于上传文件，它是用Servlet来实现的
	 * 
	 */
	protected void uploadRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxPostSize);
		request.setCharacterEncoding("UTF-8");
		try {
			List fileItems = upload.parseRequest(request);
			Iterator iter = fileItems.iterator();
			System.out.print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String aftFileName = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length());
					String preFileName = request.getParameter("fileName");
					try {
						// 写入图片
						item.write(new File(uploadPath + "\\" + preFileName+aftFileName));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}